<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" pageName="标校">
      <template v-slot:opraCurdBtn1="row">
        <span>
          <el-button
            type="primary"
            link
            size="small"
            @click="lookBtn(row.row.row)"
          >
            <img src="@/assets/images//keranqiti/折线图标.png" alt="" />
          </el-button>
          <!-- <el-button type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
          <el-button type="primary" link size="small" @click="deleteBtn(row.row.row)">删除</el-button> -->
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <!-- <el-button class="btn" type="primary" link @click="addBtn('mul')">
          <el-icon style="margin-right: 2px;">
            <svg-icon class-name="search-icon" icon-class="addtotal" />
          </el-icon>新增
        </el-button> -->
        <el-button class="btn" type="primary" link @click="deleteBtn('mul')">
          <el-icon> <DeleteFilled /> </el-icon>删除
        </el-button>
      </template>
    </list_controller>
    <!-- 新增弹框 -->
    <teleport to="body">
      <vxe-modal
        esc-closable
        destroy-on-close
        :lock-view="false"
        :width="660"
        :height="auto"
        v-model="state.addModal"
        resize
        :mask="true"
      >
        <template #title>
          <div class="w100 h100 fsc mask_title">{{ state.modalTitle }}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form
              ref="formRef"
              :model="state.formData"
              :rules="state.rules"
              label-position="top"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="传感器类型" prop="sensorType">
                    <el-select
                      clearable
                      filterable
                      v-model="state.formData.sensorType"
                      placeholder="请选择"
                      @change="sensorTypeChange"
                    >
                      <el-option
                        v-for="item in state.typegetSensorsList"
                        :key="item.sensorName"
                        :label="item.sensorName"
                        :value="item.sensorName"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="传感器安装地点" prop="typePlace">
                    <el-input
                      clearable
                      v-model="state.formData.typePlace"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="通风类型" prop="ventilateType">
                    <el-input
                      clearable
                      v-model="state.formData.ventilateType"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="传感器编号" prop="typeCode">
                    <el-select
                      clearable
                      filterable
                      v-model="state.formData.typeCode"
                      multiple
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in state.typeCodeList"
                        :key="item"
                        :label="item"
                        :value="item"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="报警浓度(%)" prop="alarmValue">
                    <el-input
                      clearable
                      v-model="state.formData.alarmValue"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="断电浓度(%)" prop="cutValue">
                    <el-input
                      clearable
                      v-model="state.formData.cutValue"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="复电浓度(%)" prop="resumeValue">
                    <el-input
                      clearable
                      v-model="state.formData.resumeValue"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="断电范围" prop="cutArea">
                    <el-input
                      clearable
                      v-model="state.formData.cutArea"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="工作面图片上传" prop="imagePath">
                    <el-upload
                      action
                      v-model:file-list="state.fileList"
                      :before-upload="beforeUpload"
                      :http-request="uploadHttpRequestAdd"
                      ref="upload"
                      list-type="picture"
                      :on-preview="handlePictureCardPreview"
                    >
                      <el-button type="primary">
                        <svg-icon
                          class-name="search-icon"
                          icon-class="photo"
                        />上传图片</el-button
                      >
                      <template #tip>
                        <div class="el-upload__tip">
                          上传图片支持jpg/png等，大小不超过 500kb
                        </div>
                      </template>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div class="form_footer">
              <el-button @click="cancel">取消</el-button>
              <el-button type="primary" @click="submitForm"> 确定 </el-button>
            </div>
          </div>
        </template>
      </vxe-modal>
    </teleport>
    <!-- 详情 -->
    <el-drawer
      v-model="state.drawerShow"
      direction="rtl"
      size="40%"
      close-on-click-modal
      :modal="true"
    >
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title">
          <svg-icon class-name="search-icon" icon-class="dot" /><span
            >图表</span
          >
        </h4>
      </template>
      <!-- <p class="drawer_sub_title">
        <svg-icon class-name="search-icon" icon-class="map" /><span>{{state.formData.typePlace}}</span>
      </p> -->
      <div>
        <el-row :gutter="20">
          <el-col :span="24">
            <div ref="chartContainer" style="width: 100%; height: 600px"></div>
          </el-col>
        </el-row>
      </div>
    </el-drawer>
    <el-dialog v-model="state.dialogVisiblepictureCardPreview">
      <img :src="state.dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup>
import list_controller from "@/components/commonCom/list_controller";
import { computed, onMounted, reactive } from "vue";
import { table_headers } from "@/components/commonCom/table_headers";
import axios from "@/utils/request";
import usePagesStore from "@/store/modules/pages";
import { gettypeCode, fileupload, gettypegetSensors } from "@/api/config";
import * as echarts from "echarts";
const { proxy } = getCurrentInstance();
const store = usePagesStore();
const upload = ref();
components: {
  list_controller;
}
let previewHttps = import.meta.env.VITE_APP_HTTP;
let state = reactive({
  dialogVisiblepictureCardPreview: false,
  dialogImageUrl: "",
  fileList: [],
  addModal: false,
  modalTitle: "新增地点类型",
  drawerShow: false,
  // 列表
  options: {
    isShowCaozuo: true,
    tableheads: computed(() => table_headers.historyCalibrationPoint),
    queryList: {
      dropdownUrl: "",
      querys: [
        {
          field: "pointNumber",
          title: "测点编号",
          type: "input",
          binddata: "",
        },
        {
          field: "pointName",
          title: "测点名称",
          type: "select",
          binddata: "",
          options: [],
        },
        {
          field: "installPlace",
          title: "安装地点",
          type: "select",
          binddata: "",
          options: [],
        },
        {
          field: "time",
          title: "标校时间",
          type: "startendtime",
          binddata: "",
        },
      ],
      queryMap: new Map([
        ["sensorTypeId", "safety_pointType"],
        ["deviceTypeId", "safety_deviceType"],
        ["alarmTypeId", "alarmType"],
      ]),
    },
    dataUrl: "/history/calibration/point/list",
    delUrl: "/history/calibration/point/",
    addUrl: "/place/type/addType",
    descUrl: "place/type/typeInfo/",
    editUrl: "/place/type/editType",
  },
  // 表单
  formRef: null,
  formData: {},
  rules: {
    sensorType: [
      {
        required: true,
        message: "请选择传感器类型",
        trigger: "change",
      },
    ],
    typePlace: [
      {
        required: true,
        message: "请输入传感器安装地点",
        trigger: "blur",
      },
    ],
    alarmValue: [
      {
        required: true,
        message: "请输入报警浓度",
        trigger: "blur",
      },
    ],
  },
  editId: undefined,
  typeCodeList: [],
  typegetSensorsList: [],
});
// 查看按钮
function lookBtn(row) {
  console.log(row, "row");
  state.drawerShow = true;
  axios
    .post("/history/calibration/point/chart", {
      substationNumber: row.substationNumber,
      pointNumber: row.pointNumber,
    })
    .then((res) => {
      if (res.data) {
        getChartsFn(res.data.xaxis, res.data.yaxis);
      }
    });
  // axios.post(state.options.descUrl + row.id).then(res => {
  //   if (res.code == 200) {
  //     state.formData = res.data
  //     state.typegetSensorsList.forEach(item => {
  //       if (item.sensorName == state.formData.sensorType) {
  //         state.typeCodeList = item.sensorCode
  //       }
  //     })
  //   }
  // })
}
function getChartsFn(xData, yData) {
  const chartContainer = proxy.$refs.chartContainer;
  const chart = echarts.init(chartContainer);
  const option = {
    xAxis: {
      type: "category",
      name: "",
      data: xData,
    },
    yAxis: {
      type: "value",
      name: "",
      nameTextStyle: {
        // color: "rgba(255, 255, 255, .8)",
        padding: [0, 0, 10, 20],
        fontSize: 12,
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "line",
        shadowStyle: {
          color: "rgba(81, 127, 253, 0.1)",
        },
        label: {
          label: {
            show: true,
            backgroundColor: "transparent",
          },
          shadowStyle: {
            color: "rgba(81, 127, 253, 0.1)",
          },
        },
      },
      backgroundColor: "#fff", // 提示框浮层的背景颜色。
      borderRadius: 5,
      textStyle: {
        // 提示框浮层的文本样式。
        // color: "#5470c6",
      },
    },
    series: [
      {
        data: yData,
        type: "line",
      },
    ],
  };
  chart.setOption(option);
}
// 新增按钮
function addBtn(row) {
  state.addModal = true;
  state.formData = {};
  state.editId = undefined;
  state.fileList = [];
}
function LastStr(str) {
  if (str) {
    let index = str.lastIndexOf("/");
    str = str.substring(index + 1, str.length);
    return str;
  }
}
// 编辑按钮
// function editBtn(row) {
//   state.modalTitle = '编辑地点类型'
//   state.addModal = true
//   axios.post(state.options.descUrl + row.id).then(res => {
//     if (res.code == 200) {
//       state.formData = res.data
//       state.fileList=[{name:LastStr(state.formData.imagePath),url:state.formData.imagePath}]
//       state.typegetSensorsList.forEach(item => {
//         if (item.sensorName == state.formData.sensorType) {
//           state.typeCodeList = item.sensorCode
//           state.formData.typeCode = state.formData.typeCode.split(',')
//         }
//       })
//       state.editId = res.data.id
//     }
//   })
// }
function handlePictureCardPreview(uploadFile) {
  state.dialogVisiblepictureCardPreview = true;
  state.dialogImageUrl = uploadFile.url;
}
//删除
function deleteBtn(row) {
  console.log(row, "row");
  let ids = [];
  if (row != "mul") {
    ids = [row.id];
  } else {
    if (store.records.length > 0) {
      ids = store.records.map((item) => {
        return item.id;
      });
    } else {
      proxy.$modal.msgSuccess("请先勾选所要删除数据!");
    }
  }
  if (ids.length > 0) {
    // 确认删除
    proxy
      .$confirm("确认删除吗？", "提示")
      .then(() => {
        axios.delete(state.options.delUrl + ids).then((res) => {
          if (res.code == 200) {
            proxy.$refs["zujianname"].getData();
            state.addModal = false;
            proxy.$modal.msgSuccess(res.msg);
            store.records = [];
          }
        });
      })
      .catch(() => {
        console.log("cancel");
      });
  }
}
/** 提交按钮 */
function submitForm() {
  if (state.formData.typeCode) {
    state.formData.typeCode = state.formData.typeCode.toString();
  }
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (state.editId) {
        state.formData.id = state.editId;
        axios.post(state.options.editUrl, state.formData).then((res) => {
          if (res.code == 200) {
            proxy.$refs["zujianname"].getData();
            state.addModal = false;
            proxy.$modal.msgSuccess(res.msg);
          }
        });
      } else {
        axios.post(state.options.addUrl, state.formData).then((res) => {
          if (res.code == 200) {
            proxy.$refs["zujianname"].getData();
            state.addModal = false;
            proxy.$modal.msgSuccess(res.msg);
          }
        });
      }
    }
  });
}

function cancel() {
  state.addModal = false;
}
// 下拉选数据
function getTypeList() {
  let pointArr = [];
  let placeArr = [];
  //测点名称
  axios.get("/history/calibration/point/pointName/list").then((res) => {
    if (res.data) {
      pointArr = res.data.map((item) => {
        return {
          label: item,
          value: item,
        };
      });
      state.options.queryList.querys[1].options = pointArr;
    }
  });
  //安装地点
  axios.get("/history/calibration/point/installPlace/list").then((res) => {
    if (res.data) {
      placeArr = res.data.map((item) => {
        return {
          label: item,
          value: item,
        };
      });
      state.options.queryList.querys[2].options = placeArr;
    }
  });
}
const fileType = ["jpg", "png", "gif", "jpg", "jpeg"]; // 允许的文件类型
const uploadHttpRequestAdd = (data) => {
  upload.value.clearFiles();
  const formData = new FormData();
  formData.append("file", data.file);
  fileupload(formData).then((res) => {
    state.formData.imagePath = previewHttps + res.fileName;
    console.log(state.formData.imagePath, "state.formData.imagePath");
    state.fileList.push({ url: state.formData.imagePath });
    proxy.$modal.msgSuccess(res.msg);
  });
};
const beforeUpload = (file) => {
  //上传前的钩子
  if (file.type != "" || file.type != null || file.type != undefined) {
    //截取文件的后缀，判断文件类型
    const FileExt = file.name.replace(/.+\./, "").toLowerCase();
    // 计算文件的大小
    const isLt5M = file.size / 1024 < 500; //这里做文件大小限制
    //如果大于500kb
    if (!isLt5M) {
      proxy.$modal.msgWarning("上传文件大小超过限制!");
      upLoading.value = 0;
      return false;
    }
    //如果文件类型不在允许上传的范围内
    if (fileType.includes(FileExt)) {
      return true;
    } else {
      proxy.$modal.msgWarning("上传文件格式不正确!");
      upLoading.value = 0;
      return false;
    }
  }
};

function sensorTypeChange(val) {
  state.typegetSensorsList.forEach((item) => {
    if (item.sensorName == val) {
      state.typeCodeList = item.sensorCode;
    }
  });
}
onMounted(() => {
  getTypeList();
  //获取路由跳转到本页面的参数
  const { start, end } = useRoute().query;
  if (start && end) {
    state.options.queryList.querys[3].binddata = [start, end];
  }
});
</script>
<style lang="scss" scoped>
</style>